var app = getApp();
var util = require('../../utils/util.js');


Page({
  data: {
    awardsList: {},  //初始化大转盘的奖项
    chance: true,  //是否有抽奖机会
    animationData: {},
    flag: true,
    times: 0, //剩余抽奖次数,
    ex_passwd:'',
    loading:false,
    disabled:false, //禁用按钮
    disable:'',     //禁用按钮样式
    act_ID: '',
    hide:true, //获取验证码窗口隐藏
    mobile:'',
    code:'',
    text:'获取验证码', //获取验证码按钮的文字
    disable_btn:false, //禁用获取验证码按钮
    disabled_confirm:false //禁用确认按钮
  },

  /*兑换显示隐藏 */
  duijiang: function (e) {
    console.log(app.globalData.userInfo)
    console.log(e)
    if (app.globalData.userInfo.User_Mobile == ''){
        this.setData({
          hide:false
        })
    }else{ 
    this.setData({
      flag: !this.data.flag,
      sn: e.currentTarget.dataset.sn,
      sn_id: e.currentTarget.dataset.sn_id
    })
    }
  },
  guanbi: function () {
    this.setData({
      flag: !this.data.flag
    })
  },


  gotoList: function () {
    wx.switchTab({
      url: '../list/list'
    })
  },
  

  //查询中奖记录
  getExRecord: function (res) {
    console.log(res);
    if (res.errorCode == 0) {
      for (var i = 0; i < res.data.length; i++) {
        res.data[i]['time'] = util.format_time('yyyy-M-d h:m', res.data[i].SN_CreateTime)
      }
      this.setData({
        record: res.data        
      })
    }
  },

  //加载页面时初始化大转盘
    onReady: function (e) {
      wx.showLoading({
        title: '加载中',
      })
    //检查用户是否登录
    if (!app.globalData.userInfo) {
      app.login('', this.load);
    } else {
      this.load();
    }

    

  },

  //初始化方法
  load: function() {
    var cateArgs = {
      User_ID: app.globalData.userInfo.User_ID,
      act: 'init_turntable'
    }
    app.http_req(cateArgs, app.globalData.init.api_url, 'POST', this.award);
  },

  //初始化大转盘,渲染转盘奖项
  award: function (res) {

    wx.hideLoading();
    if (res.errorCode == 0){
      this.setData({
        descr:res.data.turntable.descr,
        prizejson: JSON.parse(res.data.turntable.prizejson),
        startTime: util.format_time('yyyy/M/d h:s', res.data.turntable.created_at),
        endTime: util.format_time('yyyy/M/d h:s', res.data.turntable.endtimes),
        AllDayLotteryTimes_have: res.data.AllDayLotteryTimes_have,
        hasLotteryTimesByToday: res.data.hasLotteryTimesByToday,
        act_ID: res.data.turntable.id
      })
      var awardsConfig = res.data.prize;
      var that = this;

      // 绘制转盘
      //查询一共多少个奖品
      var len = awardsConfig.length,
      rotateDeg = 360 / len / 2 + 90,
      html = [],
      turnNum = 1 / len  // 文字旋转 turn 值
      for (var i = 0; i < len; i++) {

        // 奖项列表
        html.push({ turn: i * turnNum + 'turn', award: awardsConfig[i].name }); 
       
      }
  
     
      //设置WXML奖项
      that.setData({
        awardsList: html
      });
      //是否有抽奖机会
      if(res.data.chance == 0){
        this.setData({
          chance:false
        })
      } else {
        this.setData({
          times: res.data.chance
        })
      }

      //查询中奖记录
      var record = {
        User_ID: app.globalData.userInfo.User_ID,
        act: 'getExRecord',
        Act_ID: res.data.turntable.id
      }
      app.http_req(record, app.globalData.init.api_url, 'POST', this.getExRecord);
    }
  },
  //点击申请兑奖
  formSubmit:function(e){
    var exPrize = {
      act: 'exPrize',
      User_ID: app.globalData.userInfo.User_ID,
      SN_ID: this.data.sn_id,
      ex_passwd: e.detail.value.mima
    }
    if (e.detail.value.mima ==''){
      wx.showModal({
        title:'提示',
        content: '请输入兑奖密码',
        showCancel:false
      })
    }else{
      app.http_req(exPrize, app.globalData.init.api_url, 'POST', this.exPrize);
    }
    
  },
  //获取兑奖信息
  exPrize:function(res){
    console.log(res);
    this.setData({
      loading:true,
      disabled:true,
      disable:'disable'
    })
    if(res.errorCode == 0){
      this.setData({
        loading: false,
        disabled: false,
        disable: '',
        flag:true
      })
      this.setData({
        ex_passwd:''
      })
      wx.showModal({
        content: res.msg,
        showCancel:false
      });
      //查询中奖记录
      var record = {
        User_ID: app.globalData.userInfo.User_ID,
        act: 'getExRecord',
        Act_ID: this.data.act_ID
      }
      app.http_req(record, app.globalData.init.api_url, 'POST', this.getExRecord);
    } else if (res.errorCode == 2){
      this.setData({
        loading: false,
        disabled: false,
        disable: '',
        ex_passwd: ''
      })
       wx.showModal({
         content: res.msg,
         showCancel:false
       })
    } else if (res.errorCode == 403){
      this.setData({
        loading: false,
        disabled: false,
        disable: '',
        ex_passwd: ''
      })
      wx.showModal({
        content: res.msg,
        showCancel:false
      })
    }
  },

//点击抽奖
  getLottery: function () { //开始转盘

    //如果没有次数,则直接提醒,返回false
    if (this.data.times <= 0) {
      wx.showModal({
        title: '提示',
        content: '您的抽奖机会已用完',
        showCancel:false
      })
      return false;
    }
    //如果正在旋转的时候,不能再次点击
    if (!this.data.chance) {
      return false;
    }

    //开始旋转就设为false,防止多次点击问题
    this.setData({
      chance:false
    })

    //请求抽奖接口
    var cateArgs = {
      act: 'begin_turntable',
      User_ID: app.globalData.userInfo.User_ID
    }
    app.http_req(cateArgs, app.globalData.init.api_url, 'POST', this.begin_turntable);
  },
  begin_turntable: function (res) {
    if (res.errorCode == 0) {

      //获取奖项的数组长度
      var award_len = this.data.awardsList.length;
      var that = this;
      //每点击抽奖一次抽奖次数减一
      that.data.times--;
      that.setData({
        hasLotteryTimesByToday: that.data.hasLotteryTimesByToday - 1,
        AllDayLotteryTimes_have: that.data.AllDayLotteryTimes_have - 1
      })
      if (that.data.times <= 0) {
        that.setData({
          times: 0
        })
      }
      //此处是取一个随机数,生产环境下,这个awardIndex应是根据后台的概率计算出来本次获得哪个奖,此变量对应奖励中的index键
      var random = Math.random();
      var awardIndex = res.data.prize;

      // 每次转之前,要初始化 rotate,否则已经转过一定的角度,再点就不会转了,要初始化到0
      var animationInit = wx.createAnimation({
        duration: 1
      })
      this.animationInit = animationInit;
      animationInit.rotate(0).step()
      this.setData({
        animationData: animationInit.export(),
        btnDisabled: 'disabled'
      })
      //初始化完毕

      // 开始旋转抽奖
      setTimeout(function () {
        var animationRun = wx.createAnimation({
          duration: 4000,
          timingFunction: 'ease'
        })
        that.animationRun = animationRun
        //此处乘以8没有什么特别的意义,改成10,20都可以,是想让他转多少角度.
        animationRun.rotate(360 * 8 - awardIndex * (360 / award_len)).step()
        that.setData({
          animationData: animationRun.export()
        })
      }, 100)

      // 转动停止后100ms弹出中奖提示
      setTimeout(function () {
        if (res.data.prize == award_len - 1) {
          wx.showModal({
            title:'提示',
            content: res.msg,
            showCancel: false
          })
        } else {
          wx.showModal({
            title: '恭喜',
            content: res.msg,
            showCancel: false
          })
        }

        if (that.data.times > 0) {
          that.setData({
            chance:true
          })
        }

        //查询中奖记录
        var record = {
          User_ID: app.globalData.userInfo.User_ID,
          act: 'getExRecord',
          Act_ID: that.data.act_ID
        }
        app.http_req(record, app.globalData.init.api_url, 'POST', that.getExRecord);
      }, 4100);

    } else {
      wx.showModal({
        content: res.msg,
        showCancel: false
      })
    };
  },


//点击取消隐藏验证框
  cancel_btn:function(){
     this.setData({
       hide:true
     })
  },

//输入电话号
  bind_num:function(e){
     this.setData({
       mobile:e.detail.value
     })
  },
  //点击获取验证码
  get_code:function(){
    var myreg = /^[1][3,4,5,7,8][0-9]{9}$/; 
    var that = this;
    if(that.data.mobile == ''){
      wx.showModal({
        title: '提示',
        content: '请输入手机号码',
        showCancel:false
      })
    }else if(!myreg.test(that.data.mobile)){
      wx.showModal({
        title: '提示',
        content: '请输入正确的手机号码',
        showCancel: false
      })
    }else{
      var code = {
        act:'sendyzm',
        User_ID: app.globalData.userInfo.User_ID,
        Mobile: that.data.mobile
      }
      //请求获取验证码
      app.http_req(code, app.globalData.init.api_url, 'POST', that.getCode);
    }
  },
  getCode:function(res){
    var that = this
     console.log(res);
     if (res.errorCode == 0){
       wx.showToast({
         title: res.msg,
         icon:'success'
       });
       var second = 120;
       var inter = setInterval(function () {
         that.setData({
           text: '(' + second + ')' + 's后重新发送',
           disable_btn: true
         })
         second--;
         if (second < 0) {
           clearInterval(inter);
           that.setData({
             text: '获取验证码',
             disable_btn: false
           })
         }
       }, 1000)
       wx.showModal({
         title: '提示',
         content: '短信发送失败',
         showCancel: false
       })
     } else if (res.errorCode == 2){
       wx.showModal({
         title: '提示',
         content: res.msg,
         showCancel: false
       })
     } else if (res.errorCode == 500){
         wx.showModal({
           title: '提示',
           content: res.msg,
           showCancel:false
         })
     }
  },
  //输入手机验证码
  bind_code:function(e){
    this.setData({
      code:e.detail.value
    })
  },
//点击确认按钮
  confirm_btn:function(){
    var that = this;
      if(that.data.code == ''){
        wx.showModal({
          title: '提示',
          content: '请输入手机验证码',
          showCancel:false
        })
      }else{
        var verification  = {
          act: 'bindmobile',
          User_ID: app.globalData.userInfo.User_ID,
          Mobile: that.data.mobile,
          yzm:that.data.code
        }
        //请求绑定手机号
        app.http_req(verification, app.globalData.init.api_url, 'POST', that.confirm);
      }
  },
  confirm:function(res){
    var that = this;
    console.log(res);
    if(res.errorCode == 0){
      //检查用户是否登录
      app.login('reLogin', that.load);
      wx.showModal({
        title: '提示',
        content: '绑定成功',
        showCancel:false
      });
      that.setData({
        disabled_confirm:true,
        hide:true
      })
    }else if(res.errorCode == 403){
      wx.showModal({
        title: '提示',
        content: res.msg,
        showCancel: false
      })
    } else if (res.errorCode == 500) {
      wx.showModal({
        title: '提示',
        content: res.msg,
        showCancel: false
      })
    }
  }

})
